package com.shuke.sk_worm.tool;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class Opencv {

    private final String resourcesPath = "src/main/resources/";

    public Opencv(){
        String dllPath = getBasePath() + "opencv_java490.dll";
        System.load(dllPath);
    }


    public double regex(String qkImg, String bigImg){
        //对拼图图形进行处理，将滑块图片存储为Mat类型
        Mat slideBlockMat = Imgcodecs.imread(getBasePath() + qkImg);

        //1.灰度化图片
        Imgproc.cvtColor(slideBlockMat, slideBlockMat, Imgproc.COLOR_BGR2GRAY);

        //2.去除周围黑边
        for (int row = 0; row < slideBlockMat.height(); row++) {
            for (int col = 0; col < slideBlockMat.width(); col++) {
                if (slideBlockMat.get(row, col)[0] == 0) {
                    slideBlockMat.put(row, col, 96);
                }
            }
        }
        //3.转为黑白图
        Core.inRange(slideBlockMat, Scalar.all(96), Scalar.all(96), slideBlockMat);

        Imgcodecs.imwrite(getBasePath() + "kk.png", slideBlockMat);

        //对滑动背景图进行处理
        Mat slideBgMat = Imgcodecs.imread(getBasePath() + bigImg);

        //灰度化图片
        Imgproc.cvtColor(slideBgMat, slideBgMat, Imgproc.COLOR_BGR2GRAY);

        //二值化（转黑白图）
        //Core.inRange(slideBgMat, Scalar.all(96), Scalar.all(96), slideBgMat);
        Imgproc.threshold(slideBgMat,slideBgMat,127,255, Imgproc.THRESH_BINARY);

        Imgcodecs.imwrite(getBasePath() + "jj.png", slideBgMat);

        Mat g_result = new Mat();
        /*
         * 将凹槽背景和拼图进行匹配
         */
        Imgproc.matchTemplate(slideBgMat, slideBlockMat, g_result, Imgproc.TM_CCOEFF_NORMED);
        Point matchLocation = Core.minMaxLoc(g_result).maxLoc;
        //返回匹配点的横向举例
        return matchLocation.x*340/552;

    }

    private String getBasePath(){
        //获取绝对路径
        return System.getProperty("user.dir") + "/";
    }

    //读取当前路径
    private String getPath(){
        String res = getBasePath();
        return res.replace('\\','/') + resourcesPath;
    }
}
